﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace PlaceHR.Processor.Processor.Salary.Steps
{
    class OtherSalaryStepCalculator : StepCalculatorBase<SalaryProcessorContext, EmployeeSalary>
    {
        public override void Calculate(SalaryProcessorContext context, EmployeeSalary employeeSalary)
        {
            // 将多余的假期换算成工资
            int checkMaxVacationMonth = 2;
            if (ConfigurationManager.AppSettings["CheckMaxVacationMonth"] != null)
            {
                checkMaxVacationMonth = Convert.ToInt32(ConfigurationManager.AppSettings["CheckMaxVacationMonth"]);
            }

            if (checkMaxVacationMonth != context.CurrentEngine.Month)
            {
                return;
            }

            string officeCode = context.CurrentEmployee.OfficeDepartment_lnk.FirstOrDefault().OfficeCode;

            VacationSettings currentSettings = context.HRDBContext.VacationSettings.FirstOrDefault(p => !p.IsDeleted
                        && (string.IsNullOrWhiteSpace(p.OfficeCode) || p.OfficeCode.Equals(officeCode, StringComparison.OrdinalIgnoreCase))
                        && (string.IsNullOrWhiteSpace(p.EmployeeTypeCode) || p.EmployeeTypeCode.Equals(context.CurrentEmployee.EmployeeTypeCode, StringComparison.OrdinalIgnoreCase))
                        && (string.IsNullOrWhiteSpace(p.VacationTypeCode) || p.VacationTypeCode.Equals(VacationType.AnnualLeave, StringComparison.OrdinalIgnoreCase)));

            if (currentSettings == null)
            {
                return;
            }

            VacationBase currentVacationBase = context.HRDBContext.VacationBase.FirstOrDefault(p => p.EmployeeID == context.CurrentEmployee.EmployeeID
                                    && !p.IsDeleted
                                    && p.IsCurrent
                                    && p.VacationTypeCode != null
                                    && p.VacationTypeCode.Equals(VacationType.AnnualLeave, StringComparison.OrdinalIgnoreCase));

            if(currentVacationBase == null)
            {
                return;
            }

            var payHours = currentVacationBase.FinalHours.GetValueOrDefault() - currentSettings.MaxDays.GetValueOrDefault() * context.WorkingHoursPerDay;
            if (payHours <= 0)
            {
                return;
            }

            var totalSalary = (employeeSalary.BasicSalary ?? 0)
                                    + (employeeSalary.PositionSalary ?? 0)
                                    + (employeeSalary.Bonus ?? 0);

            employeeSalary.Others = (totalSalary / context.WorkingDaysPerMonth) * (payHours / context.WorkingHoursPerDay);
            currentVacationBase.FinalHours = currentSettings.MaxDays.Value * context.WorkingHoursPerDay;

        }

    }
}
